package com.slw.emergency.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slw.emergency.entity.OverseaEpidemic;
import com.slw.emergency.mapper.OverseaEpidemicMapper;
import com.slw.emergency.model.RespOverseaEpidemic;
import com.slw.emergency.service.OverseaEpidemicService;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

/**
 * @Author: x18266
 * @Description:
 * @Date: Created in 15:30 2020/2/19
 */
@Service
public class OverseaEpidemicServiceImpl extends ServiceImpl<OverseaEpidemicMapper, OverseaEpidemic> implements OverseaEpidemicService {
    public List<RespOverseaEpidemic> getOversea(){
        Date today = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String todayDate = df.format(today);
        String currentDate = todayDate;
        List<RespOverseaEpidemic> todayResult = this.baseMapper.getOversea(todayDate);
        if(todayResult.size() == 0){
            String yestDate = getSpecifiedDayBefore(todayDate);
            todayResult = this.baseMapper.getOversea(yestDate);
            currentDate = yestDate;
        }
        String str = getDateString(currentDate);
        todayResult.forEach(epidemic -> {
            epidemic.setUpdateTime(getDateString(str));
        });

        return todayResult;
    }

    public String getDateString(String date){
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date res = new Date();
        try {
            res = df1.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
        return df2.format(res);
    }

    public String getSpecifiedDayBefore(String specifiedDay){
        Calendar c = Calendar.getInstance();
        Date date=null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day=c.get(Calendar.DATE);
        c.set(Calendar.DATE,day-1);
        String dayBefore=new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return dayBefore;
    }
}
